from django.shortcuts import render, HttpResponse, redirect
from django.http import JsonResponse
from django.forms import Form, fields, widgets
from app01 import models
from app01.forms.forms import ClassForm, StudentForm, TeacherForm, LoginForm
from app01.utils.page import PageInfo
from django.db.models import Q


# Create your views here.


# def classes(request):
#     # tk = request.COOKIES.get('ticket')
#     # print(tk)
#     # if not tk:
#     #     return redirect('/login/')
#     class_list = sqlhelper.get_list("select id,title from class", [])
#     return render(request, 'classes.html', {'class_list': class_list})


def classes(request):
    if request.method == 'GET':
        # class_list = models.Class.objects.all()
        # return render(request, 'classes.html', {'class_list': class_list})
        all_count = models.Class.objects.all().count()
        page_info = PageInfo(request.GET.get('page'), all_count, '/classes/', 15, 5)
        # PageInfo(当前页[request获取]，数据总量[.all()获取]，每页数据量，显示页码数)
        class_list = models.Class.objects.all()[page_info.start():page_info.end()]
        form = ClassForm()
        return render(request, 'classes.html', {'class_list': class_list, 'page_info': page_info, 'form': form})
    form = ClassForm(request.POST)
    if form.is_valid():
        form.save()
        return JsonResponse({'status': True})
    return JsonResponse({'status': False, 'error': form.errors})


def add_cls(request):
    if request.method == 'GET':
        obj = ClassForm()
        return render(request, 'add_class.html', {'obj': obj})
    else:
        obj = ClassForm(request.POST)
        if obj.is_valid():
            models.Class.objects.create(**obj.cleaned_data)
            return redirect('/classes/')
        return render(request, 'add_class.html', {'obj': obj})


def edit_cls(request, nid):
    if request.method == 'GET':
        row = models.Class.objects.filter(id=nid).first()
        # 让页面显示初始值
        # obj = ClassForm(data={'title': 'asdfasdfasdfas'})
        obj = ClassForm(initial={'title': row.title})
        return render(request, 'edit_class.html', {'nid': nid, 'obj': obj})
    else:
        obj = ClassForm(request.POST)
        if obj.is_valid():
            models.Class.objects.filter(id=nid).update(**obj.cleaned_data)
            return redirect('/classes/')
        return render(request, 'edit_class.html', {'nid': nid, 'obj': obj})


def del_cls(request, nid):
    models.Class.objects.filter(id=nid).delete()
    return redirect('classes')


def students(request):
    if request.method == 'GET':
        # stu_list = models.Student.objects.all()
        # return render(request, 'students.html', {'stu_list': stu_list})
        all_count = models.Student.objects.all().count()
        page_info = PageInfo(request.GET.get('page'), all_count, '/students/', 15, 5)
        # PageInfo(当前页[request获取]，数据总量[.all()获取]，每页数据量，显示页码数)
        stu_list = models.Student.objects.all()[page_info.start():page_info.end()]
        form = StudentForm()
        return render(request, 'students.html', {'stu_list': stu_list, 'page_info': page_info, 'form': form})
    form = StudentForm(request.POST)
    print('进来了')
    if form.is_valid():
        print('储存数据')
        models.Student.objects.create(**form.cleaned_data)
        return JsonResponse({'status': True})
    print('错了')
    return JsonResponse({'status': False, 'error': form.errors})


def add_stu(request):
    if request.method == 'GET':
        obj = StudentForm()
        return render(request, 'add_stu.html', {'obj': obj})
    else:
        obj = StudentForm(request.POST)
        if obj.is_valid():
            # print(obj.cleaned_data)
            models.Student.objects.create(**obj.cleaned_data)
            return redirect('students')
        return render(request, 'add_stu.html', {'obj': obj})


def edit_stu(request, nid):
    if request.method == "GET":
        row = models.Student.objects.filter(id=nid).values('name', 'mail', 'age', 'cls_id').first()
        obj = StudentForm(initial=row)
        return render(request, 'edit_stu.html', {'nid': nid, 'obj': obj})
    else:
        obj = StudentForm(request.POST)
        if obj.is_valid():
            models.Student.objects.filter(id=nid).update(**obj.cleaned_data)
            return redirect('/student/')
        return render(request, 'edit_stu.html', {'nid': nid, 'obj': obj})


def del_stu(request, nid):
    models.Student.objects.filter(id=nid).delete()
    return redirect('classes')


def teachers(request):
    if request.method == 'GET':
        # tea_list = models.Teacher.objects.all()
        # return render(request, 'teachers.html', {'tea_list': tea_list})
        all_count = models.Teacher.objects.all().count()
        page_info = PageInfo(request.GET.get('page'), all_count, '/teachers/', 15, 5)
        # PageInfo(当前页[request获取]，数据总量[.all()获取]，每页数据量，显示页码数)
        tea_list = models.Teacher.objects.all()[page_info.start():page_info.end()]
        form = TeacherForm()
        return render(request, 'teachers.html', {'tea_list': tea_list, 'page_info': page_info, 'form': form})
    form = TeacherForm(request.POST)
    if form.is_valid():
        clss = form.cleaned_data.pop('clss')
        row = models.Teacher.objects.create(**form.cleaned_data)
        row.c2t.add(*clss)
        return JsonResponse({'status': True})
    return JsonResponse({'status': False, 'error': form.errors})


def add_tea(request):
    if request.method == "GET":
        obj = TeacherForm()
        return render(request, 'add_tea.html', {'obj': obj})
    else:
        obj = TeacherForm(request.POST)
        if obj.is_valid():
            clss = obj.cleaned_data.pop('clss')
            row = models.Teacher.objects.create(**obj.cleaned_data)
            row.c2t.add(*clss)  # [1,2]
            return redirect('/teachers/')
        return render(request, 'add_tea.html', {'obj': obj})


def edit_tea(request, nid):
    if request.method == "GET":
        row = models.Teacher.objects.filter(id=nid).first()
        class_ids = row.c2t.values_list('id')
        # print(class_ids)    --<QuerySet [(1,), (2,)]>
        id_list = list(zip(*class_ids))[0] if list(zip(*class_ids)) else []
        # print(id_list)  ---(1, 2)
        # obj = TeacherForm(initial={'tame':row.name,'xx':[1,2,3]})
        obj = TeacherForm(initial={'name': row.name, 'clss': id_list})
        return render(request, 'edit_tea.html', {'nid': nid, 'obj': obj})
    else:
        obj = TeacherForm(request.POST)
        if obj.is_valid():
            clss = obj.cleaned_data.pop('clss')  # ['2', '4']
            li = []
            for i in range(len(clss)):
                j = int(clss[i])
                li.append(j)
            # print(li) #[1, 2]
            # print(*clss)    # 2 4
            models.Teacher.objects.filter(id=nid).update(**obj.cleaned_data)
            row = models.Teacher.objects.filter(id=nid).first()
            row.c2t.set(li)  # [1,2]
            return redirect('/teachers/')
        return render(request, 'edit_tea.html', {'obj': obj})


def del_tea(request, nid):
    models.Teacher.objects.filter(id=nid).delete()
    return redirect('teachers')


# 添加教师和编辑教师的班级不会跟随数据库联动
# 数据库响应不及时


# def login(request):
#     if request.method == 'GET':
#         return render(request, 'login.html')
#     else:
#         u = request.POST.get('user')
#         p = request.POST.get('pwd')
#         if u == 'root' and p == 'root':
#             obj = redirect('/classes/')
#             obj.set_cookie('ticket', 'zheshicookie', max_age=10)
#             # import datetime
#             # from datetime import timedelta
#             # ct = datetime.datetime.utcnow()
#             # v = timedelta(seconds=10)
#             # print('ct',ct)  #ct 2021-01-31 08:58:52.318210
#             # print('v',v)    #v 0:00:10
#             return obj
#         else:
#             return render(request, 'login.html', {'msg': '用户名或密码错误'})


def login(request):
    if request.method == 'GET':
        form = LoginForm()
        return render(request, 'login.html', {'form': form})
    form = LoginForm(request.POST)
    if form.is_valid():
        name = form.cleaned_data['user']
        password = form.cleaned_data['password']
        # 姓名或账号登录
        user_object = models.UserInfo.objects.filter(Q(name=name) | Q(account=name)).filter(password=password).first()
        if user_object:
            request.session['user_id'] = user_object.id  # 写入名为userid的session
            # 设置session超时时间1小时
            request.session.set_expiry(60*60)
            # 用户名密码正确
            return redirect('classes')
        form.add_error('user', '用户名或密码错误')
    return render(request, 'login.html', {'form': form})


def logout(request):
    request.session.flush()
    return redirect('/login/')


def user(request):
    user_list = models.UserInfo.objects.all()
    return render(request, 'user.html', {'user_list': user_list})


def ajax_login(request):
    import json
    ret = {'status': True, 'error': None}
    form = LoginForm(request.POST)
    if form.is_valid():
        print('进来了')
        name = request.POST.get('user')
        password = request.POST.get('password')
        # 姓名或账号登录
        user_object = models.UserInfo.objects.filter(Q(name=name) | Q(account=name)).filter(password=password).first()
        # 如果符合字段规则，但账号密码不正确
        if not user_object:
            print('密码错了')
            return JsonResponse({"status": False, 'error': form.errors})
        request.session['user_id'] = user_object.id  # 写入名为userid的session
        # 设置session超时时间1小时
        request.session.set_expiry(60)
        return JsonResponse({"status": True, 'data': "/classes/"})
    print('字段错了')
    ret['status'] = False
    ret['error'] = form.errors
    print(ret)
    v = json.dumps(ret)
    return HttpResponse(v)
